package com.usyk;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * User: oleksii.usyk@gmail.com
 * Date: 03.01.12
 * Time: 23:05
 */
public class Level {

    private String name;
    private Map<Level, Double> nextLevelsRating;

    public Map<Level, Double> getResult() {

        if (nextLevelsRating == null) return null;
        Map<Level, Map<Level, Double>> toMultiply = new HashMap<Level, Map<Level, Double>>();
        for (Level level : nextLevelsRating.keySet()) {
            toMultiply.put(level, level.getResult());
        }

        return multiply(toMultiply, nextLevelsRating);
    }

    private static Map<Level, Double> multiply(Map<Level, Map<Level, Double>> nextLevels, Map<Level, Double> currLevel) {

        //just to retrieve some element doesn't matter each
        Level[] levels = currLevel.keySet().toArray(new Level[currLevel.keySet().size()]); //BUT, PR, ...


        Map<Level, Double> result = new HashMap<Level, Double>();

        if (nextLevels.get(levels[0]) == null) {
            return currLevel;
        }

        for (Level resultLevel : nextLevels.get(levels[0]).keySet()) {
            Double doubleResult = 0d;

            for (Level outerLevel : currLevel.keySet()) { // SOUTH, EAST, WEST, CENTER
                doubleResult += currLevel.get(outerLevel) * nextLevels.get(outerLevel).get(resultLevel);
            }

            result.put(resultLevel, doubleResult);
        }


        return result;
    }

    public void modifyKeys(Set<Level> keys) {
        Map<Level, Double> tempMap = new HashMap<Level, Double>();
        for (Level l : keys) {
            tempMap.put(l, nextLevelsRating.get(l));
        }
        nextLevelsRating = tempMap;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Map<Level, Double> getNextLevelsRating() {
        return nextLevelsRating;
    }

    public void setNextLevelsRating(Map<Level, Double> nextLevelsRating) {
        this.nextLevelsRating = nextLevelsRating;
    }

//    @Override
//    public String toString() {
//        return "{ name='" + name + '\'' +
//                ", nextLevelsRating = " + nextLevelsRating + '}';
//    }

    @Override
    public String toString() {
        return "\n'" + name + "\'";

    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Level level = (Level) o;

        if (name != null ? !name.equals(level.name) : level.name != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return name != null ? name.hashCode() : 0;
    }
}
